package com.lilosoft.business.task;

import com.github.pagehelper.PageInfo;
import com.lilosoft.business.cga.models.*;
import com.lilosoft.business.cga.service.*;
import com.lilosoft.business.precity.models.*;
import com.lilosoft.business.precity.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 小峰
 * Date: 2019-08-28
 * Time: 11:23
 *
 * @author Administrator
 */
@Component
public class SynchronousPreCity {

    private Logger logger = LoggerFactory.getLogger(SynchronousPreCity.class);
    @Autowired
    private CgaCaseService cgaCaseService;
    @Autowired
    private EgsProjectService egsProjectService;
    @Autowired
    private EgsProjectsummaryService egsProjectsummaryService;
    @Autowired
    private CgaCaseRelatedPersonService cgaCaseRelatedPersonService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private CgaCaseMaterialService cgaCaseMaterialService;
    @Autowired
    private EgsProjectMaterialsService egsProjectMaterialsService;
    @Autowired
    private CgaCaseTacheService cgaCaseTacheService;
    @Autowired
    private CgaSupportExecutionService cgaSupportExecutionService;
    @Autowired
    private SysAttachmentService sysAttachmentService;


    @Autowired
    private TemporaryProjectService temporaryProjectService;


    @Autowired
    private UpProAcceptService upProAcceptService;
    @Autowired
    private UpProAcceptIndividualService upProAcceptIndividualService;
    @Autowired
    private UpProAcceptUnitService upProAcceptUnitService;
    @Autowired
    private UpProMaterialService upProMaterialService;
    @Autowired
    private UpProProcessService upProProcessService;
    @Autowired
    private UpProSpecialprocedureService upProSpecialprocedureService;
    @Autowired
    private UpProResultService upProResultService;
    @Autowired
    private UpProAttachmentService upProAttachmentService;
    @Autowired
    private UpDataReconciliationService upDataReconciliationService;

    private List<String> primaryKeys;

    /**
     * 同步前置库处理
     *
     * @param cgaCase
     */
    public void synchronousMethos(CgaCase cgaCase) {
        try {

            //测试的事项中间表
            TemporaryProject temporaryProject = temporaryProjectService.selectByProjectNO(cgaCase.getProjectNo());
            if (temporaryProject == null) {
                return;
            }

            EgsProject egsProject = egsProjectService.selectByProjectId(cgaCase.getProjectId());
            EgsProjectsummary egsProjectsummary = egsProjectsummaryService.selectByProjectId(cgaCase.getProjectId());
            CgaCaseRelatedPerson cgaCaseRelatedPerson = cgaCaseRelatedPersonService.selectByCaseId(cgaCase.getCaseId());
            SysDept sysDept = sysDeptService.selectByDeptId(cgaCase.getAcceptDeptId());
            if (egsProject == null || egsProjectsummary == null || cgaCaseRelatedPerson == null || sysDept == null) {
                return;
            }
            // 办件受理信息
            UpProAccept upProAccept = upProAcceptService.upProAcceptSynchronous(cgaCase, egsProject,
                    egsProjectsummary, cgaCaseRelatedPerson, sysDept, temporaryProject);
            if (null == upProAccept) {
                return;
            }
            System.out.println("====================有数据,CaseID:" + cgaCase.getCaseId());

            UpProAcceptIndividual upProAcceptIndividual = null;
            UpProAcceptUnit upProAcceptUnit = null;
            if ("1".equals( upProAccept.getApplyertype())) {
                //申请自然人信息
                upProAcceptIndividualService.UpProAcceptIndividualSynchronous(upProAccept, cgaCaseRelatedPerson);

            } else {
                //申请法人信息
                upProAcceptUnitService.UpProAcceptUnitSynchronous(upProAccept, cgaCaseRelatedPerson);

            }

            List<CgaCaseMaterial> cgaCaseMaterialList = cgaCaseMaterialService.selectByCaseId(cgaCase.getCaseId());
            for (CgaCaseMaterial cgaCaseMaterial : cgaCaseMaterialList) {
                EgsProjectMaterials egsProjectMaterials = egsProjectMaterialsService.selectByPrimaryKey(cgaCaseMaterial.getMaterialId());
                if (null == egsProjectMaterials) {
                    continue;
                }
                //材料目录信息
                UpProMaterial upProMaterial = upProMaterialService.UpProMaterialSynchronous(upProAccept, cgaCaseMaterial, egsProjectMaterials);

                upProAttachmentService.UpProAttachmentSynchronous(upProMaterial,
                        sysAttachmentService.selectByPrimaryKey(cgaCaseMaterial.getFileId()));
            }

            List<CgaCaseTache> cgaCaseTaches = cgaCaseTacheService.selectByCaseId(cgaCase.getCaseId());
            for (CgaCaseTache cgaCaseTach : cgaCaseTaches) {
                // 办理过程信息
                UpProProcess upProProcess = upProProcessService.UpProProcessSynchronous(upProAccept, cgaCaseTach);

                List<CgaSupportExecution> cgaSupportExecutions = cgaSupportExecutionService.selectByCaseId(cgaCase.getCaseId());
                for (CgaSupportExecution cgaSupportExecution : cgaSupportExecutions) {
                    // 特别程序信息
                   upProSpecialprocedureService.UpProSpecialprocedureSynchronous(upProProcess, upProAccept, cgaSupportExecution);
                }
            }
            //办件结果信息
            upProResultService.UpProResultSynchronous(upProAccept, egsProjectsummary, cgaCase, cgaCaseMaterialList.size());

            //将 CGACase表中的 IS_PRECITY 更新为1
            if (null != primaryKeys) {
                primaryKeys.add(cgaCase.getId());
            }
            //cgaCaseService.updateIsPrecityById(cgaCase);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("执行调用时出现异常,CaseId为:" + cgaCase.getCaseId() + ",主键Id:" + cgaCase.getId(), ex);
        }
    }



    //执行处理
    private void invokeSynchronous(CgaCaseExample example) {
        if (null == example) {
            return;
        }
        CgaCaseExample.Criteria criteria = example.getOredCriteria().get(0);
        criteria.andIsPrecityIsNull();
        criteria.andCaseStateIn(Arrays.asList("09", "12", "13"));
        int countPage = 5;
        int countTotal = 0;
        PageInfo<CgaCase> cgaCasePageInfo = null;
        primaryKeys = new ArrayList<>();
        for (int i = 1; i <= countPage; i++) {
            cgaCasePageInfo = cgaCaseService.selectByExample(example, i);
            if (i == 1) {
                countTotal = ((Long) cgaCasePageInfo.getTotal()).intValue();
            }
            countPage = cgaCasePageInfo.getPages();
            for (CgaCase cgaCase : cgaCasePageInfo.getList()) {
                synchronousMethos(cgaCase);
            }
        }
        logger.info("查询到的总数据为:" + countTotal);
        logger.info("同步数据量:" + primaryKeys.size());
        System.out.println("查询到的总数据为:" + countTotal + "|||| 同步数据量:" + primaryKeys.size());
        cgaCaseService.updateIsPrecityByPrimaryKeyList(primaryKeys);
        upDataReconciliationService.countdataByCDbatch();

    }


    /**
     * 根据时间查询处理
     *
     * @param beginDate
     * @param endDate
     */
    public void invokeSynchronousByDate(Date beginDate, Date endDate) {
        CgaCaseExample example = new CgaCaseExample();
        CgaCaseExample.Criteria criteria = example.createCriteria();
        if (beginDate != null) {
            //criteria.andRegisterTimeGreaterThanOrEqualTo(beginDate);
            criteria.andEndTimeGreaterThanOrEqualTo(beginDate);
        }

        criteria.andEndTimeLessThan(endDate == null ? new Date() : endDate);
        //if (endDate != null) {
        //    criteria.andRegisterTimeLessThan(endDate);
        //} else {
        //    criteria.andRegisterTimeLessThan(new Date());
        //}
        invokeSynchronous(example);
    }

    /**
     * 根据CaseId查询处理
     *
     * @param caseId
     */
    public void invokeSynchronousByCaseId(String caseId) {
        CgaCaseExample example = new CgaCaseExample();
        CgaCaseExample.Criteria criteria = example.createCriteria();
        criteria.andCaseIdEqualTo(caseId);
        invokeSynchronous(example);
    }
}
